use crossterm::{
    cursor::{self, MoveTo}, event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers, MediaKeyCode, ModifierKeyCode}, terminal, ExecutableCommand, QueueableCommand
};
use std::io::{self,stdout,Write};
use crate::Position;
pub struct Size{
    pub width:u16,
    pub height:u16,
}
pub struct Terminalu{
   size:Size,
   _stdout:Result<(),std::io::Error>,
}
impl Terminalu{
    /**
     * 获取终端的大小，并进入raw 模式
     */
    pub fn default()->Result<Self,std::io::Error>{
        let size=terminal::size()?;
        Ok(Self{
            size:Size{
                width:size.0,
                height:size.1,
            },
            _stdout:terminal::enable_raw_mode(),
        })
    }
    /**
     * 清空终端
     */
    pub fn clear_screen(){
        //print!("{}",terminal::Clear(terminal::ClearType::All));
        stdout().execute(terminal::Clear(terminal::ClearType::All))
    }
    /* pub fn cursor_position(x:u16,y:u16){
        let x=x.saturating_add(1);
        let y=y.saturating_add(1);
        stdout().execute(cursor::MoveTo(x,y));

    } */
   /**
    * 移动光标到指定位置
    */
   #[allow(clippy::cast_possible_truncation)]
   pub fn cursor_position(position:&Position){
    let Position{mut x,mut y}=position;
    let x=x.saturating_add(1);
    let y=y.saturating_add(1);
    let x=x as u16;
    let y=y as u16;
    stdout().execute(cursor::MoveTo(x,y));

}
   /**
    * 刷新缓冲区内容到终端
    */
    pub fn flush()->Result<(),std::io::Error>{
        stdout().flush()
    }
    /**
     * 返回终端大小
     */
    pub fn size(&self)->&Size{
        &self.size
    }
    /**
     * 隐藏光标
     */
    pub fn cursor_hide(){
        stdout().execute(cursor::Hide);
    }
    /**
     * 显示光标
     */
    pub fn show_cursor(){
        stdout().execute(cursor::Show);
    }
    /**
     * 按行清楚终端内容
     *      */
    pub fn clear_current_line(){
        stdout().execute(terminal::Clear(terminal::ClearType::CurrentLine));
    }
    

}
